/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.post.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.poemmanager.domain.vo.QueryCriteria;
import me.zhengjie.poemmanager.mapper.CommentMapper;
import me.zhengjie.poemmanager.mapper.FavoritesMapper;
import me.zhengjie.poemmanager.mapper.ObjectLikeMapper;
import me.zhengjie.poemmanager.util.ExtractUtil;
import me.zhengjie.post.domain.Post;
import me.zhengjie.post.domain.vo.PostQueryCriteria;
import me.zhengjie.post.mapper.PostMapper;
import me.zhengjie.post.service.PostService;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @description 服务实现
* @author hwl
* @date 2024-12-06
**/
@Service
@RequiredArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    private final PostMapper postMapper;
    private final CommentMapper commentMapper;
    private final ObjectLikeMapper objectLikeMapper;
    private final FavoritesMapper favoritesMapper;


    @Override
    public PageResult<Post> queryAll(PostQueryCriteria criteria, Page<Object> page){
        // 获取基础分页数据
        IPage<Post> postIPage =postMapper.findAll(criteria, page);
        return PageUtil.toPage(postIPage);

    }

    @Override
    public List<Post> queryAll(PostQueryCriteria criteria){
        return postMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer create(Post resources) {
        save(resources);
        return resources.getPostId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Post resources) {
        Post post = getById(resources.getPostId());
        post.copy(resources);
        saveOrUpdate(post);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Post> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Post post : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", post.getUserName());
            map.put("标题", post.getTitle());
            map.put("主要内容", post.getContent());
            map.put("创建时间", post.getCreatedAt());
            map.put("修改时间", post.getUpdatedAt());
            map.put("状态", post.getStatus() == 0 ? "正常" : "已删除"); // 状态转义
            map.put("帖子类型", post.getType() == 0 ? "日常讨论贴" : "诗歌解析贴"); // 新增类型
            map.put("诗歌标题", post.getPoemTitle()); // 新增诗歌信息
            map.put("诗歌作者", post.getPoemAuthor());
            map.put("关联诗歌ID", post.getPoemId());
            map.put("评论数", post.getCommentCount()); // 新增互动数据
            map.put("收藏数", post.getFavoriteCount());
            map.put("点赞数", post.getLikeCount());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<Post> getMyPost(String userId) {
        List<Post>posts=postMapper.getPostByUserId(userId);
        for (Post post:
             posts) {
            String content= ExtractUtil.extrac(post.getContent()).replaceAll("\\s*|\r|\n|\t","");
            if(content.length()>50)
                content=content.substring(0,50);
            post.setContent(content);
        }
        return posts;
    }

    @Override
    public Post getPostById(Integer postId) {
        Post p=postMapper.getPostById(postId);
        p.setTag(postMapper.getTags(postId));
        p.setComments(commentMapper.getPostCommentByObjectId(postId));
//        for (Comment c:p.getComments()
//             ) {
//            c.setCountLike(commentMapper.getCountLike(c.getCommentId()));
//
//        }
        return p;
    }

    @Override
    public List<QueryCriteria> queryByTitle(String title) {
        return postMapper.queryByTitle(title);
    }

    @Override
    public List<Post> getPoemExplanation() {
        List<Post>ps=postMapper.getPoemExplanation();
        for (Post p:ps
             ) {
            String content= ExtractUtil.extrac(p.getContent()).replaceAll("\\s*|\r|\n|\t","");
            if(content.length()>50)
                content=content.substring(0,50);
            p.setContent(content);
            p.setCommentCount(postMapper.getCommentCount(p.getPostId()));
            p.setTag(postMapper.getTags(p.getPostId()));
        }
        return ps;
    }

    @Override
    public String createByUser(Post post) {
        save(post);
        for (String s:post.getTag()
             ) {
            postMapper.insertTag(s,post.getPostId());
        }
        return "创建成功";
    }

    @Override
    public List<Post> getCommunication() {
        List<Post>ps=postMapper.getCommunication();
        for (Post p:ps
        ) {
            String content= ExtractUtil.extrac(p.getContent()).replaceAll("\\s*|\r|\n|\t","");
            if(content.length()>50)
                content=content.substring(0,50);
            p.setContent(content);
            p.setCommentCount(postMapper.getCommentCount(p.getPostId()));
            p.setTag(postMapper.getTags(p.getPostId()));
        }
        return ps;
    }

    @Override
    public List<Post> getMyFavoritePost(String userName) {
        List<Post>ps=postMapper.getMyFavoritePost(userName);
        for (Post p:ps
        ) {
            String content= ExtractUtil.extrac(p.getContent()).replaceAll("\\s*|\r|\n|\t","");
            if(content.length()>50)
                content=content.substring(0,50);
            p.setContent(content);
            p.setTag(postMapper.getTags(p.getPostId()));
        }
        return ps;
    }
}